package utils;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;


/**
 * @Author: Cyy
 * @Description:
 * @Date:Created in 11:20 2019/5/23
 */
public class HbaseUtils {

    HBaseAdmin admin = null;
    Configuration configuration =null;

    private HbaseUtils(){
        configuration = new Configuration();
        configuration.set(HConstants.ZOOKEEPER_QUORUM,"10.2.29.101:2181");
//        configuration.set("hbase.rootdir","hdfs://atlantis:8082/hbase");
        try {
            admin= new HBaseAdmin(configuration);

        }catch (IOException e){
            e.printStackTrace();
        }
    }
        private static HbaseUtils instance = null;

    public static synchronized HbaseUtils getInstance(){
        if(instance == null){
            instance=new HbaseUtils();
        }
        return instance;
    }
    //添加表
    public void createHTable(String tableName,String cf) throws IOException {
        HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(tableName));
        tableDescriptor.addFamily(new HColumnDescriptor(cf));
        admin.createTable(tableDescriptor);
    }
    //获取表实例
    public HTable getHTable(String tableName){
            HTable hTable = null;
        try {
            hTable = new HTable(configuration,tableName);
        }catch (IOException e){
            e.printStackTrace();
        }
            return hTable;
    }
    //添加表记录
    public void put(String tableName,String rowkey,String cf,String column,String value){
        HTable hTable=getHTable(tableName);
        Put put  =new Put(Bytes.toBytes(rowkey));
        put.addColumn(Bytes.toBytes(cf),Bytes.toBytes(column),Bytes.toBytes(value));

        try {

        hTable.put(put);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void  main(String[] args) throws IOException {
//        HbaseUtils.getInstance().createHTable("test","info");

        HTable hTable=HbaseUtils.getInstance().getHTable("test");
        System.out.println(hTable.getName().getNameAsString());

        HbaseUtils.getInstance().put("test","20190523_12","info","click_count","100");
        HbaseUtils.getInstance().put("test","20190523_12","info","page_traffic","100");


    }







}
